package com.fjwt.gz.mch.ctrl.coupon;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.coupon.SelfOperatedCouponsImpl;
import com.fjwt.gz.db.dto.AwardCouponDTO;
import com.fjwt.gz.db.dto.PointDTO;
import com.fjwt.gz.db.entity.AwardCouponEntity;
import com.fjwt.gz.db.entity.FansMchEntity;
import com.fjwt.gz.db.entity.MchChannelEntity;
import com.fjwt.gz.db.entity.MchInfoEntity;
import com.fjwt.gz.db.vo.FansMchVO;
import com.fjwt.gz.mch.ctrl.CommonCtrl;
import com.fjwt.gz.service.impl.*;
import com.fjwt.gz.service.mapper.ActivityMapper;
import com.fjwt.gz.util.Utils;
import com.fjwt.gz.zhyx.sms.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/***
 * 卡券奖品管理
 * @Author: Will
 * @Date: 2025-03-26
 * @Version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/api/award/coupon")
public class GtCouponController extends CommonCtrl {
    @Autowired
    protected FansMchService fansMchService;
    @Autowired
    protected MchInfoService mchInfoService;
    @Autowired
    protected SelfOperatedCouponsImpl selfOperatedCoupons;
    @Autowired
    protected FansPayService fansPayService;
    @Autowired
    protected ActivityService activityService;
    @Autowired
    protected MchChannelService mchChannelService;
    @Autowired
    protected AwardCouponService awardCouponService;
    @Autowired
    protected ActivityMapper activityMapper;


    /**
     * 新增卡券奖品
     *
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @Transactional
    public ApiRes add() throws Exception {
        AwardCouponEntity awardCouponEntity = getObject(AwardCouponEntity.class);
        String appId = request.getHeader("appid");
        String phone = mchInfoService.getById(awardCouponEntity.getMchNo()).getPhone();

        JSONObject smsCode = SmsUtil.getSmsCOde(CS.SYS_ROLE_TYPE.MCH, phone, 8);
        if (null == smsCode) {
            throw new BizException("验证码已过期！");
        }
        String smsCodeRedis = smsCode.getString("code");
        if (!smsCodeRedis.equals(awardCouponEntity.getCode())) {
            throw new BizException("验证码错误");
        }

        if (TextUtils.isEmpty(awardCouponEntity.getCouponName())) {
            return ApiRes.customFail("卡券名称不能为空，请检查！");
        }
        if (ObjectUtils.isEmpty(awardCouponEntity.getPayAmount())) {
            return ApiRes.customFail("卡券起付金额不能为空，请检查！");
        }

        if (null != awardCouponEntity.getCouponNum() && null != awardCouponEntity.getCouponPrice()) {
            if (awardCouponEntity.getPayAmount() <= awardCouponEntity.getCouponPrice()) {
                throw new BizException("卡券起付金额不能小于卡券面额");
            }
            int num = awardCouponEntity.getCouponNum();
            int price = awardCouponEntity.getCouponPrice();
            awardCouponEntity.setCouponAmount(num * price);
        }
        awardCouponEntity.setCouponType(6);
        awardCouponEntity.setCreatedAt(new Date());
        awardCouponEntity.setBatchNo(Utils.generateBathNo());//后端生成批次号
        awardCouponEntity.setCreatedUid(getCurrentUser().getUserId());
        Long userId = getCurrentUser().getUserId();
        String outRequestNo = System.currentTimeMillis() + "1";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("outRequestNo", outRequestNo);
        awardCouponEntity.setPayConfig(String.valueOf(jsonObject));
        Long fansId = getCurrentUser().getFansId();
        fansMchService.add(awardCouponEntity, userId, fansId, appId);

        return ApiRes.ok();
    }

    /**
     * 回显修改详情
     */
    @PostMapping("/upCouponInfo")
    public ApiRes upCouponInfo() throws Exception {
        AwardCouponEntity awardCouponEntity = getObject(AwardCouponEntity.class);
        Long activityId = getValLong("activityId");
        if (null == activityId) {
            return ApiRes.customFail("网络波动，请稍后重试！");
        }
        Long fansId = getCurrentUser().getFansId();
        fansMchService.upCouponInfo(activityId, fansId, awardCouponEntity);
        return ApiRes.ok();
    }


    //新增商户接口
    @PostMapping("/addFile")
    public ApiRes addFile() throws Exception {
        JSONObject jsonObject = getObject(JSONObject.class);
        String locationAgentNo =request.getHeader("locationAgentNo");
        String codeJsonStr = RedisUtil.getString(CS.getCouponMchUserCode(CS.SYS_ROLE_TYPE.MCH, jsonObject.getString("phone")));
        if (StringUtils.isEmpty(codeJsonStr)) {
            throw new BizException("验证码已过期，请重新点击发送验证码！");
        }
        JSONObject codeJson = JSONObject.parseObject(codeJsonStr);
        String cacheCode = codeJson.getString("code");
        if (StringUtils.isEmpty(cacheCode) || !cacheCode.equalsIgnoreCase(jsonObject.getString("code"))) {
            throw new BizException("验证码错误！");
        }
        if (StringUtils.isEmpty(jsonObject.getString("mchNo"))) {
            throw new BizException("商户号不能为空！");
        }
        JSONObject instmch = selfOperatedCoupons.instmch(jsonObject.getString("mchNo"), jsonObject.getString("phone"));


        String data = instmch.getString("data");
        if (data != null && data.length() >= 2 && data.startsWith("[") && data.endsWith("]")) {
            data = data.substring(1, data.length() - 1);
        }
        JSONObject dataJson = JSONObject.parseObject(data);
        if (JSONUtil.isNull(dataJson)) {
            throw new BizException("手机号和商户号不匹配，请确认后重试");
        }

        if (JSONUtil.isNull(instmch.getString("code"))) {
            throw new BizException("网络连接异常,请稍后重试");
        }

        MchInfoEntity mchNo = mchInfoService.getById(jsonObject.getString("mchNo"));
        
        if (ObjectUtils.isEmpty(mchNo)) {
//            mchNo = new MchInfoEntity();
//            extracted(mchNo, dataJson, jsonObject);
//            mchInfoService.save(mchNo);
            throw new BizException("商户号不存在，请重新填写商户号！");
        }else {
            extracted(mchNo, dataJson, jsonObject);
            mchInfoService.updateById(mchNo);
        }

        LambdaQueryWrapper<MchChannelEntity> fansMch = MchChannelEntity.gw();
        fansMch.eq(MchChannelEntity::getMchNo, jsonObject.getString("mchNo"));
        fansMch.eq(MchChannelEntity::getIfCode, jsonObject.getString("gtpay"));
        MchChannelEntity mchChannelEntities = mchChannelService.getOne(fansMch);
        if (JSONUtil.isNull(mchChannelEntities)) {
            MchChannelEntity mchChannelEntity = new MchChannelEntity();
            mchChannelEntity.setMchNo(jsonObject.getString("mchNo"));
            mchChannelEntity.setIfCode("gtpay");
            mchChannelEntity.setIfName("国通");
            mchChannelEntity.setWechatSubmerchantNo(dataJson.getString("wxMercNo"));
            mchChannelEntity.setAliSubmerchantNo(dataJson.getString("zfbMercNo"));
            mchChannelService.save(mchChannelEntity);
        } else {
            mchChannelEntities.setWechatSubmerchantNo(dataJson.getString("wxMercNo"));
            mchChannelEntities.setAliSubmerchantNo(dataJson.getString("zfbMercNo"));
            mchChannelService.updateById(mchChannelEntities);
        }

        LambdaQueryWrapper<MchChannelEntity> mchChannbel = MchChannelEntity.gw();
        mchChannbel.eq(MchChannelEntity::getMchNo, jsonObject.getString("mchNo"));
        MchChannelEntity mchChannelEntity = mchChannelService.getOne(mchChannbel);

        if (JSONUtil.isNull(mchChannelEntity)) {
            MchChannelEntity intmch = new MchChannelEntity();
            intmch.setMchNo(jsonObject.getString("mchNo"));
        }


        FansMchEntity fansMchEntity = new FansMchEntity();
        Long fansId = getCurrentUser().getFansId();
        fansMchEntity.setFansId(fansId);
        fansMchEntity.setMchNo(jsonObject.getString("mchNo"));
        fansMchEntity.setCreatedAt(new Date());
        fansMchEntity.setUpdateAt(new Date());
        try {
            fansMchService.save(fansMchEntity);
        } catch (Exception e) {
            throw new BizException("当前商户已被绑定！");
        }
        List<FansMchVO> list = fansMchService.getSaveFile(fansId, locationAgentNo);
        List<FansMchVO> vos = List.copyOf(list);
        return ApiRes.ok(vos);
    }

    private void extracted(MchInfoEntity mchNo, JSONObject dataJson, JSONObject jsonObject) {
        JSONObject mch = JSONObject.from(mchNo);
        mch.put("dataJson", dataJson);
        mchNo.setRemark(String.valueOf(mch));
        mchNo.setPhone(jsonObject.getString("phone"));
        mchNo.setMchName(dataJson.getString("mrchName"));
        mchNo.setAddress(dataJson.getString("storeAddress"));
        mchNo.setMchListImage(dataJson.getString("storeLogo"));
        mchNo.setAreaName(dataJson.getString("province") + "," + dataJson.getString("city") + "," + dataJson.getString("district"));
        mchNo.setLocation(null);
    }


    // 绑定商户数量接口
    @PostMapping("/saveFile")
    public ApiRes saveFile() {
        Long fansId = getCurrentUser().getFansId();
        String locationAgentNo =request.getHeader("locationAgentNo");
        List<FansMchVO> saveFile = fansMchService.getSaveFile(fansId,locationAgentNo);
        List<FansMchVO> vos = List.copyOf(saveFile);
        return ApiRes.ok(vos);
    }

    //校验用户授权
    @PostMapping("/couponPayAuth")
    public ApiRes couponPayAuth() {
        Long fansId = getCurrentUser().getFansId();
        String awardId = getValString("awardId");
        if (null == fansId || awardId.isEmpty()) {
            return ApiRes.customFail("网络波动，请稍后重试！");
        }
        JSONObject object = fansPayService.getcouponPayAuth(fansId, awardId);
        return ApiRes.ok(object);
    }

    /**
     * 用户卡券查询
     */
    @PostMapping("/selectactivities")
    public ApiRes selectProcess() {
        List<AwardCouponDTO> list = fansMchService.selectProcess();
        List<AwardCouponDTO> vos = List.copyOf(list);
        return ApiRes.ok(vos);
    }


    /**
     * 商家卡券查询
     */
    @PostMapping("/selectActivitiesMch")
    public ApiRes selectProcessMch() {
        Long fansId = getCurrentUser().getFansId();
        Integer state = getValInteger("state");
        if (state == null || null == fansId) {
            return ApiRes.customFail("网络波动，请稍后重试！");
        }
        List<AwardCouponDTO> list = activityService.selectProcessMch(fansId, state);
        List<AwardCouponDTO> vos = List.copyOf(list);
        return ApiRes.ok(vos);
    }

    /**
     * 商家信息修改
     */
    @PostMapping("/updateProcessMch")
    public ApiRes updateProcessMch() {
        PointDTO location = getVal("location", PointDTO.class);
        MchInfoEntity mchInfo = getObject(MchInfoEntity.class);
        if (mchInfo == null) {
            return ApiRes.customFail("网络波动，请稍后重试！");
        }
        return ApiRes.ok(activityService.updateProcessMch(mchInfo,location));
    }

    /**
     * 商家卡券下架
     */
    @PostMapping("/removeActivitiesMch")
    public ApiRes removeActivitiesMch() {

        String activityId = getValString("activityId");
        String awardId = getValString("awardId");
        if (activityId == null) {
            return ApiRes.customFail("网络波动，请稍后重试！");
        }
        return ApiRes.ok(activityService.removeActivitiesMch(activityId, awardId));
    }

    /**
     * 卡券详情
     */
    @PostMapping("/couponDetail")
    public ApiRes couponDetail() {
        Long activityId = getValLong("activityId");
        String mchNo = getValString("mchNo");
        if (activityId == null || mchNo == null) {
            return ApiRes.customFail("网络波动，请稍后重试！");
        }
        return ApiRes.ok(awardCouponService.couponDetail(mchNo, activityId));
    }

    /**
     * 商户信息
     */
    @PostMapping("/mchInfo")
    public ApiRes mchInfo() {
        String mchNo = getValString("mchNo");
        if (mchNo == null) {
            return ApiRes.customFail("网络波动，请稍后重试！");
        }
        MchInfoEntity mchInfo = mchInfoService.mchInfo(mchNo);
        MchInfoEntity data = new MchInfoEntity();
        BeanUtils.copyProperties(mchInfo, data);
        return ApiRes.ok(data);
    }

    /**
     * 商户卡券信息
     */
    @PostMapping("/mchCouponInfo")
    public ApiRes mchCouponInfo() {
        Integer state = getValInteger("state");
        Long fansId = getCurrentUser().getFansId();

        if (fansId == null || state == null) {
            return ApiRes.customFail("网络波动，请稍后重试！");
        }
        IPage<AwardCouponDTO> awardCouponDTOIPage = awardCouponService.mchCouponInfo(getIPage(), fansId, state);
        return ApiRes.page(awardCouponDTOIPage);
    }


}
